import {call, put, takeLatest, takeEvery, select} from 'redux-saga/effects'
import * as types from '../../const/actionTypes'
import myWebSocket from '../../util/socket/YfSocket'
import config from '../../../config'
import * as  actions from '../actions/socket'
import {getMsgMap} from '../selectors/socket'
import {getNowChatUserId} from '../selectors/socket'
import {getUserId} from '../selectors/user'
import MsgCenter from '../../util/socket/MsgCenter'

/**
 * 启动socket
 * @returns {IterableIterator<*>}
 */
export function* initSocket() {
    const userId = yield select(getUserId)
    yield call(myWebSocket.initWebSocket, config.wsPath, userId, msgHandler)
}


export function* sendMsg(action) {
    const {type, chatType, content} = action.payload
    let fromUserId = yield select(getUserId)
    let toUserId = yield select(getNowChatUserId)
    let msgObject = yield call(myWebSocket.sendMsg, type, chatType, fromUserId, toUserId, content)
    console.log(JSON.stringify(msgObject))
    yield call(msgHandler, msgObject)

}

/**
 * 处理消息 发送的消息 或者接受的消息 下载用户头像等操作 等等其它解析 然后存储或者渲染 //TODO
 * @param msg
 */
export function* msgHandler(msgObject) {
    //连接回复 与 心跳回复  不处理
    if (msgObject.type == MsgCenter.MsgType.CONNECT || msgObject.type == MsgCenter.MsgType.KEEPALIVE) {
        return;
    }
    let userId = yield select(getUserId)  //自己的Id
    let nowChatUserId = yield select(getNowChatUserId) //当前正在聊天的人
    let chatUserId = MsgCenter.getChatUserId(userId, msgObject) //获取这条消息聊天对象的Id
    yield call(completeUserInfo, msgObject)
    let msgMap = yield select(getMsgMap)
    //存储到Map 会重新渲染视图
    msgMap = yield call(MsgCenter.pushToMap, chatUserId, msgObject, msgMap, nowChatUserId)
    yield put(actions.UPDATE_MSGMAP(msgMap))
}

/**
 * 完善用户头像信息 TODO
 * @param msgObject
 * @returns {IterableIterator<*>}
 */
export function* completeUserInfo(msgObject) {
    const userInfo = {
        "1": {
            userId: '1',
            name: '周杰',
            avatar: 'http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJI3gMNKKsSQichjViaoibnZuHqzTRkhGngI0vAOMMA3mID1Y2mab7EFcn46uNO8dyAMnFWOgUMfVibhQ/0'
        },
        "2": {
            userId: '2',
            name: '黄飞',
            avatar: 'http://wx.qlogo.cn/mmopen/vi_32/n6uaXic9MFiaa2WFQicqjnpAD3kC5uuECXtqUKvPd0ibicKJSFgyUCceywgKerGjJcEWjpbRHLckquxux3UbmUj3J1A/0'
        },
    }
    let fromUserId = msgObject.fromuserid
    let toUserId = msgObject.touserid
    msgObject.fromusername = userInfo[fromUserId].name
    msgObject.fromuseravatar = userInfo[fromUserId].avatar
    msgObject.touseravatar = userInfo[toUserId].avatar
    msgObject.tousername = userInfo[toUserId].name

}


/**
 * 监听Socket启动
 * @returns {IterableIterator<*>}
 */
export function* watchSocket() {
    yield takeLatest(types.REQUEST_SOCKET, initSocket)
    yield takeEvery(types.SEND_MSG, sendMsg)
}